<template>
  <view>
    <view class="box-bg">
      <uni-nav-bar :height="80" title="首页" :border="false" backgroundColor="#f5f5f5" color="#000000">
        <template #left>
          <image src="/static/xiaoxi.png" style="width: 30rpx; height: 30rpx;"></image>
        </template>
      </uni-nav-bar>
    </view>
   
	<view style="margin-right: -100rpx; margin-bottom: 10rpx; height: 50rpx; background-color: #fff;" >
		<block><span style="margin-left: 70rpx;"></span></block>
		<image src="/static/dingwei.png" style="width: 30rpx; height: 30rpx; padding-left: 15rpx;" @click="goPositioning"></image>
		<!-- 判断 chooseCity 是否为空，不为空则显示 chooseCity 的值 -->
		<text @click="goPositioning">{{ chooseCity ? chooseCity : locationCity }}</text>
		<block  @click="getWarpweft">
			<image src="/static/shuaxin1.png" style="width: 25rpx; height: 25rpx; margin-right: 10rpx;" @click="getWarpweft"></image>
			<text style="color: #2979ff" @click="getWarpweft">{{po_tips}}</text>
		</block>
	</view>
    <view class="nav">
      <view class="nav_item" @click="goMaintenance1()">
        <view style="background-color: #ff007f;">
          <image src="/static/添加车辆图标.png"></image>
        </view>
        <view>车辆维修</view>
      </view>
      <view class="nav_item" @click="goMaintenance2()">
        <view style="background-color: #aaaaff;">
         <image src="/static/添加车辆图标.png"></image>
       </view>
        <view>汽车保养</view>
      </view>
      <view class="nav_item" @click="goMaintenance3()">
        <view style="background-color: #ffaa7f;">
          <image src="/static/添加车辆图标.png"></image>
        </view>
        <view>专业洗车</view>
      </view>
      <view class="nav_item" @click="gorEfuelingList">
        <view style="background-color: #aaaa7f;">
          <image src="/static/添加车辆图标.png"></image>
        </view>
        <view>就近加油</view>
      </view>
    </view>
    <view class="nearby">
      <view class="title">
        <view class="title_left">
          <view>附近加油站</view>
          <view>根据您的位置推荐最近的加油站</view>
        </view>
        <view class="title_right" @click="gorEfuelingList">
          <view>更多</view>
          <image src="/static/dayu.png"></image>
        </view>
      </view>
      <view class="page-body">
        <map style="width: 100%; height: 200px;" :latitude="latitude" :longitude="longitude"
             :markers="covers" :scale="15"></map>
      </view>
    </view>
    <view class="nearby">
      <view class="title">
        <view class="title_left">
          <view>优惠团购</view>
        </view>
        <view class="title_right" @click="goDiscountPurchase()">
          <view>更多</view>
          <image src="/static/dayu.png"></image>
        </view>
      </view>
      <view class="discount">
        <view class="discountItem" @click="goDiscountPurchaseInfo()">
          <image src="/static/gugong.png"></image>
          <view>北京四日追花拍摄秘籍-故宫</view>
        </view>
        <navigator class="discountItem" @click="goDiscountPurchaseInfo()">
          <image src="/static/gugong.png"></image>
          <view>北京四日追花拍摄秘籍-故宫</view>
        </navigator>
      </view>
    </view>
    <MagicNavigationBar
      :items="items"
      :digHolePosition="1"
      :selectedColor="selectedColor"
      :color="color"
      @onTabSelect="onTabSelect"
      :current="currentTab"
      :background-color="backgroundColor"
      :screenBackgroundColor="screenBackgroundColor"
      :indicatorPadding="indicatorPadding"
      :indicatorSize="indicatorSize"
      :indicatorBackground="indicatorBackground">
      <template #indicatorContent>
        <view style="display: flex; justify-content: center; width: 100%; height: 100%;">
          <image @click="goEmergency" :src="img" style="width: 30px; height: 30px; align-self: center;"></image>
        </view>
      </template>
    </MagicNavigationBar>
  </view>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount, onBeforeMount} from 'vue'
import MagicNavigationBar from '../../uni_modules/jorbin-DigHoleNavigationBar/components/jorbin-DigHoleNavigationBar/jorbin-DigHoleNavigationBar.vue'
import emitter from '../../event-bus.js'
// 使用 ES Module 导入图片资源
import warningImg from '@/static/warning.png'
import indexLine from '@/static/index_line.png'
import shouye from '@/static/index.png'
import myLine from '@/static/my_line.png'
import myIcon from '@/static/my.png'
import maps from 'qqmap'
import store from "../../store";

// 引入SDK核心类，js文件根据自己业务，位置可自行放置
	var QQMapWX = require('../../static/qqmap-wx-jssdk.min.js');
	var qqmapsdk;

// 响应式变量
const covers = ref([])
const latitude = ref('')
const longitude = ref('')
const gasStations = ref([])
const locationCity = ref('')
const locationCitypro = ref('')
const img = ref(warningImg)
const selectedColor = ref('#2979ff')
const color = ref('#666666')
const currentTab = ref(0)
const backgroundColor = ref('#ffffff')
const screenBackgroundColor = ref('#f5f5f5')
const indicatorPadding = ref(8)
const indicatorSize = ref(75)
const indicatorBackground = ref('#ff0000')
const po_tips = ref('刷新')
const chooseCity = ref('')

const items = ref([
  {
    icon: {
      src: indexLine,
      width: 30,
      height: 30
    },
    text: '首页',
    selectedIcon: {
      src: shouye
    },
    url: '/pages/index/index'
  },
  {
    type: 'indicator',
    text: '上传',
    url: '/pages/emergencyRescue/emergencyRescue'
  },
  {
    icon: {
      src: myLine,
      width: 30,
      height: 30
    },
    text: '我的',
    selectedIcon: {
      src: myIcon
    },
    url: '/pages/my/my'
  }
])


//跳转方法
function goToDes(des) {
  uni.redirectTo({
    url: des
  })
}
// 方法定义
function goEmergency() {
  uni.redirectTo({
    url: '/pages/emergencyRescue/emergencyRescue'
  })
}

function onTabSelect(index, item) {
  uni.redirectTo({
    url: item.url
  })
}

function goPositioning() {
  uni.navigateTo({
    url: '/packageIndex/selectCity/selectCity'
  })
}
// 汽车维修
function goMaintenance1() {
  uni.navigateTo({
    url: `/packageIndex/repair/repairMap/repairMap`
  })
}
// 汽车保养
function goMaintenance2() {
  uni.navigateTo({
    url: `/packageIndex/car-service/car-service-map/car-service-map`
  })
}
// 专业洗车
function goMaintenance3() {
  uni.navigateTo({
    url: `/packageIndex/car-wash/car-wash-map/car-wash-map`
  })
}
// 优惠团购列表
function goDiscountPurchase() {
  uni.navigateTo({
    url: `/packageIndex/DiscountPurchase/DiscountPurchase`
  })
}
//优惠团购跳转
function goDiscountPurchaseInfo(){
	uni.navigateTo({
	  url: `/packageIndex/DiscountPurchaseInfo/DiscountPurchaseInfo`
	})
}


function gorEfuelingList() {
  uni.navigateTo({
    url: '/packageIndex/refuelingList/refuelingList?gasStations=' +
         encodeURIComponent(JSON.stringify(gasStations.value)) +
         "&covers=" + encodeURIComponent(JSON.stringify(covers.value))
  })
}

function getLocation() {
  // 使用腾讯地图 IP 定位接口
  uni.request({
    url: 'https://apis.map.qq.com/ws/location/v1/ip',
    data: {
      key: 'GZ3BZ-GIY67-NPZXM-H463Z-Q7NAE-UUFCU'
    },
    success: (res) => {
      if (res.data.status === 0) {
        const lat = res.data.result.location.lat
        const lng = res.data.result.location.lng
		getAddress(lat, lng)
        latitude.value = lat
        longitude.value = lng
        uni.setStorage({
          key: 'latitude',
          data: latitude.value
        })
        uni.setStorage({
          key: 'longitude',
          data: longitude.value
        })
        searchNearbyGasStations(lat, lng)
		console.log(lat,lng)
        
      } else {
        console.error('定位失败:', res.data.message)
      }
    },
    fail: (err) => {
      console.error('请求失败:', err)
    }
  })
}

// 通过腾讯地图搜索城市名获取经纬度
function  getLocationByCityName(chooseCity){
	console.log(chooseCity.value)
	  qqmapsdk.geocoder({
	    address: chooseCity.value, // 目标城市名称，如“北京市”
	    success: (res) => {
	      if (res.status === 0 && res.result) {
			  const lat = res.result.location.lat
			  const lng = res.result.location.lng
	        const location = res.result.location;
	        console.log('经纬度：', location.lat, location.lng);
			latitude.value = lat
			longitude.value = lng
			uni.setStorage({
			  key: 'latitude',
			  data: latitude.value
			})
			uni.setStorage({
			  key: 'longitude',
			  data: longitude.value
			})
			searchNearbyGasStations(lat, lng)
	      } else {
	        console.error('解析失败：', res.message);
	      }
	    },
	    fail: (err) => {
	      console.error('接口调用失败：', err);
	    }
	  });

};

function getAddress(latitude, longitude) {
  uni.request({
    url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=3WWBZ-P7I6Q-Q6C5V-2NNUZ-WYXYE-QABW6`,
    success: (res) => {
      if (res.data.status === 0) {
        const result = res.data.result
        locationCity.value = result.address
        locationCitypro.value = result.address_component.province
      }
    },
    complete: () => {
      uni.hideLoading()
    }
  })
}

function searchNearbyGasStations(lat, lng) {
  const keyword = '加油站'
  const location = `${lat},${lng}`
  qqmapsdk.search({
    keyword: keyword,
    location: location,
    page_size: 10,
    success: (res) => {
      gasStations.value = res.data || []
      covers.value = gasStations.value.map(item => ({
        id: item.location.lat,
        latitude: item.location.lat,
        longitude: item.location.lng,
        iconPath: '/static/weizhi1.png',
        width: 15,
        height: 20,
        callout: {
          content: item.title,
          color: '#ffffff',
          bgColor: '#007AFF',
          fontSize: 8,
          padding: 5,
          borderRadius: 20,
          displat: 'BYCLICK'
        }
      }))
      const currentMarker = {
        id: latitude.value,
        latitude: latitude.value,
        longitude: longitude.value,
        iconPath: '/static/weizhi2.png',
        width: 15,
        height: 25,
        callout: {
          content: '当前位置',
          color: '#ffffff',
          bgColor: '#007AFF',
          fontSize: 8,
          padding: 5,
          borderRadius: 20,
          displat: 'BYCLICK'
        }
      }
      covers.value.push(currentMarker)
    },
    fail: (err) => {
      console.error('搜索失败:', err)
    }
  })
}

function goToOilStation() {
  uni.navigateTo({
    url: '/packageIndex/RefuelNearby/RefuelNearby?gasStations=' +
         encodeURIComponent(JSON.stringify(gasStations.value))
  })
}

// 使用 mitt 事件总线替换原来的 eventBus
const tabHandler = (event) => {
  currentTab.value = event.index
  if (event.index !== 1) {
    uni.redirectTo({
      url: event.item.url,
      fail: (err) => {
        console.error('页面跳转失败:', err)
      }
    })
  }
}

onBeforeMount(async () => {
  // console.log(store.getters["token/getIsLogin"])
  // console.log(store.getters["token/getUsername"])
  // console.log(store.getters["token/getUserID"])
  // console.log(store.getters["token/getToken"])
  if (!store.getters["token/getIsLogin"]){
    uni.redirectTo({
      url: '/pages/login/login'
    })
  }
})



onMounted(async () => {
  emitter.on('tabSelected', tabHandler)
  if (!uni.getStorageSync('token')) {
    uni.navigateTo({
      url: '/packageMy/login/login'
    })
  }
  uni.$on('choosect',d=>{  
		 // console.log(d.chooseCity);//{参数名1: 1,参数名2: {a:1,b:2}}
		   chooseCity.value = d.chooseCity
		   console.log(chooseCity.value)
		   if (chooseCity.value) {
		           // 通过腾讯地图搜索 chooseCity 中的城市名获取经纬度
		           getLocationByCityName(chooseCity);
		       }else{
		   		  getLocation()
		   	  }
	 })
	 console.log(chooseCity.value)
  qqmapsdk = new QQMapWX({
    key: 'GZ3BZ-GIY67-NPZXM-H463Z-Q7NAE-UUFCU'
  })
  // getLocationByCityName(chooseCity.value);
  // if (chooseCity.value) {
  //         // 通过腾讯地图搜索 chooseCity 中的城市名获取经纬度
  //         getLocationByCityName(chooseCity.value);
  //     }else{
		  getLocation()
	 //  }
})

onBeforeUnmount(() => {
  emitter.off('tabSelected', tabHandler)
})

// 点击刷新获取经纬度（定位）
const getWarpweft = () => {
	chooseCity.value = '';
    po_tips.value = '定位中...';
	// 使用腾讯地图 IP 定位接口
	uni.request({
	  url: 'https://apis.map.qq.com/ws/location/v1/ip',
	  data: {
	    key: 'GZ3BZ-GIY67-NPZXM-H463Z-Q7NAE-UUFCU'
	  },
	  success: (res) => {
	    if (res.data.status === 0) {
	      const lat = res.data.result.location.lat
	      const lng = res.data.result.location.lng
		  console.log(lat)
		  console.log(lng)
		 latitude.value = lat
		 longitude.value = lng
		 uni.setStorage({
		   key: 'latitude',
		   data: latitude.value
		 })
		 uni.setStorage({
		   key: 'longitude',
		   data: longitude.value
		 })
		 searchNearbyGasStations(lat, lng)
	      uni.request({
	        url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=3WWBZ-P7I6Q-Q6C5V-2NNUZ-WYXYE-QABW6`,
	        success: (res) => {
	          if (res.data.status === 0) {
	            const result = res.data.result
	            locationCity.value = result.address
	            // locationCitypro.value = result.address_component.province
	          }
	        }
	      })
	    } else {
	      console.error('定位失败:', res.data.message)
	    }
	  },
	  fail: (err) => {
	    console.error('请求失败:', err)
	  }
	})
    setTimeout(() => {
        po_tips.value = '重新定位';
    }, 1700); 
};




</script>

<style scoped>
::v-deep .uni-nav-bar{    
        font-size: 20px;    
}
.pages {
  background-repeat: no-repeat;
  background-position: top left;
  background-size: 750rpx 365rpx;
  padding-bottom: 210rpx;
}

.nav {
  background-color: #fff;
  display: flex;
  justify-content: space-around;
  width: 720rpx;
  margin: 0 auto;
  border-radius: 15rpx;
  padding: 40rpx 0 25rpx;
}

.nav_item > view:nth-child(1) {
  width: 112rpx;
  height: 90rpx;
  line-height: 120rpx;
  text-align: center;
  border-radius: 20rpx;
}

.nav_item > view > image {
  width: 100rpx;
  height: 60rpx;
  padding-left: 5rpx;
}

.nav_item > view {
  font-size: 25rpx;
  text-align: center;
}

.nav_item > view:nth-child(2) {
  padding-top: 10rpx;
}

.nearby {
  background-color: #fff;
  width: 680rpx;
  margin: 0 auto;
  border-radius: 15rpx;
  margin-top: 20rpx;
  padding: 20rpx 20rpx;
}

.title {
  display: flex;
}

.title_left {
  margin-right: auto;
}

.title_left > view:nth-child(1) {
  font-size: 32rpx;
}

.title_left > view:nth-child(2) {
  margin-top: 6rpx;
  font-size: 20rpx;
  color: #999;
}

.title_right {
  display: flex;
  align-items: center;
  font-size: 24rpx;
}

.title_right > image {
  width: 34rpx;
  height: 34rpx;
  padding-top: 4rpx;
}

.discount {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-top: 10rpx;
}

.discountItem {
  margin-bottom: 15rpx;
  font-size: 24rpx;
  margin-top: 10rpx;
}

.discountItem > image {
  width: 325rpx;
  height: 180rpx;
  border-radius: 10rpx;
}

.discountItem > view {
  width: 320rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
}

.page-body {
  margin-top: 20rpx;
}
</style>
